package org.sith.taskrunner.managedbeans;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.sith.taskrunner.api.user.User;
import org.sith.taskrunner.ejb.services.UserManagerService;


@ManagedBean(name = "usermanager")
@SessionScoped
public class UserManagedBean {
    public static final String USER_SESSION_KEY = "user";
    private String login;
    private String password;

    @EJB(name = "UserManagerServiceEJB")
    private UserManagerService userManagerService;


    public String makeLogin() {
        User user = userManagerService.getUserByNameAndPassword(login, password);
        FacesContext context = FacesContext.getCurrentInstance();
        if (user == null) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Login Failed!",
                    "The password specified is not correct.");
            context.addMessage(null, message);
            return null;
        }

        context.getExternalContext().getSessionMap().put(USER_SESSION_KEY, user);
        return Urls.APP_MAIN;
    }

    public String logout() {
        HttpSession session = (HttpSession)
                FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return Urls.USER_LOGIN_OUTCOME;

    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
